package com.blockmeta.bbs.minemodule.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.gson.GsonUtil;
import com.blockmeta.bbs.businesslibrary.activity.CustomQrCodeActivity;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseFragment;
import com.blockmeta.bbs.businesslibrary.business.UmengEvent;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.launch.contactusYMAL;
import com.blockmeta.bbs.businesslibrary.net.pojo.UserToken;
import com.blockmeta.bbs.businesslibrary.pojo.ContactUSPOJO;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.DeepLinkUtils;
import com.blockmeta.bbs.businesslibrary.util.DialogUtil;
import com.blockmeta.bbs.businesslibrary.util.RouterActivityHelper;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.minemodule.R;
import com.blockmeta.bbs.minemodule.activity.AirDropListActivity;
import com.blockmeta.bbs.minemodule.activity.CaptureUserResultActivity;
import com.blockmeta.bbs.minemodule.activity.ContactUsActivity;
import com.blockmeta.bbs.minemodule.activity.FeedbackActivity;
import com.blockmeta.bbs.minemodule.activity.HtmlInviteActivity;
import com.blockmeta.bbs.minemodule.activity.MineSettingActivity;
import com.blockmeta.bbs.minemodule.activity.MyActiveActivity;
import com.blockmeta.bbs.minemodule.activity.MyCollectionActivity;
import com.blockmeta.bbs.minemodule.activity.MyMessageActivity;
import com.blockmeta.bbs.minemodule.activity.MyPostsActivity;
import com.blockmeta.bbs.minemodule.activity.PushManagerActivity;
import com.blockmeta.bbs.minemodule.activity.SettingActivity;
import com.blockmeta.bbs.minemodule.activity.TaskCenterActivity;
import com.bumptech.glide.Glide;
import com.king.zxing.Intents;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import io.reactivex.functions.Consumer;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;


/**
 * Created by author on 2017/12/26.
 */
@Route(path = RouterPath.MINE_FRAGMENT)
public class MineFragment extends BaseFragment implements View.OnClickListener {

    private View v;
    public static final int REQUEST_CODE_SCAN = 0X01;
    private LinearLayout click_top;

    private RelativeLayout click3;
    private RelativeLayout click4;
    private RelativeLayout click5, pushManager;

    private ImageView click8;
    private TextView login_tv;
    private LinearLayout after_login;
    private TextView name;
    private TextView id;
    private TextView coins;
    private RelativeLayout click10;
    private RelativeLayout click9;
    private RelativeLayout taskCenter;
    private CircleImageView icon;
    private RelativeLayout click11;
    private RelativeLayout click12;
    private String uClickEvent = "";
    private ImageView floatClick;
    private RelativeLayout click14;
    private UserToken.ActivityInfoBean mActivityInfoBean;
    private TextView tvVersion;
    private ImageView ivMessageHint;
    private RelativeLayout clickFocus;
    private ImageView scan;
    ContactUSPOJO sContactUSPOJO = contactusYMAL.getContactUSPOJO();

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        v = LayoutInflater.from(mContext).inflate(R.layout.fragment_mine_new, null);
        EventBus.getDefault().register(this);
        return v;
    }

    @Override
    public void initView() {
        //我的头像
        icon = (CircleImageView) v.findViewById(R.id.mine_icon);
        //进入个人中心点击时间
        click_top = (LinearLayout) v.findViewById(R.id.mine_top);
        //消息中心
        click3 = (RelativeLayout) v.findViewById(R.id.mine_click3);
        //我的收藏
        click4 = (RelativeLayout) v.findViewById(R.id.mine_click4);
        //我的活动
        click5 = (RelativeLayout) v.findViewById(R.id.mine_click5);
        //我的关注
        clickFocus = (RelativeLayout) v.findViewById(R.id.mine_click_focus);
        //任务中心
        taskCenter = v.findViewById(R.id.mine_task_center);


        //设置中心
        click8 = (ImageView) v.findViewById(R.id.mine_click8);
        //意见反馈
        click9 = (RelativeLayout) v.findViewById(R.id.mine_click9);
        //推荐好友
        click10 = (RelativeLayout) v.findViewById(R.id.mine_click10);
        //联系我们
        click11 = (RelativeLayout) v.findViewById(R.id.mine_click11);
        //我的帖子
        click12 = (RelativeLayout) v.findViewById(R.id.mine_click12);
        //推送管理
        pushManager = v.findViewById(R.id.mine_push_manager);
        //未读消息小红点提醒
        ivMessageHint = v.findViewById(R.id.iv_message_hint);

        //空投活动
        click14 = (RelativeLayout) v.findViewById(R.id.mine_click14);
        //悬浮 活动广告
        floatClick = (ImageView) v.findViewById(R.id.active_floatclick);
        //版本号
        tvVersion = (TextView) v.findViewById(R.id.mine_version);

        scan = (ImageView) v.findViewById(R.id.mine_scan);

        click_top.setOnClickListener(this);

        click3.setOnClickListener(this);
        click4.setOnClickListener(this);
        click5.setOnClickListener(this);
        taskCenter.setOnClickListener(this);

        click8.setOnClickListener(this);
        click9.setOnClickListener(this);
        click10.setOnClickListener(this);
        click11.setOnClickListener(this);
        click12.setOnClickListener(this);
        pushManager.setOnClickListener(this);
        clickFocus.setOnClickListener(this);

        click14.setOnClickListener(this);
        floatClick.setOnClickListener(this);
        scan.setOnClickListener(this);

        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        tvVersion.setText(String.format("V %s", provider.getProjectBuildInfo().version_name));

        //登陆之后的处理
        login_tv = (TextView) v.findViewById(R.id.mine_tv);
        after_login = (LinearLayout) v.findViewById(R.id.mine_after_login);
        name = (TextView) v.findViewById(R.id.mine_name);
        id = (TextView) v.findViewById(R.id.mine_id);
        coins = v.findViewById(R.id.mine_coins);
        coins.setOnClickListener(this);
        String activityInfo = SharedPreferenceUtil.getString(mContext, Constant.Activity_Info, "");
        mActivityInfoBean = GsonUtil.buildGson().fromJson(activityInfo, UserToken.ActivityInfoBean.class);
        if (mActivityInfoBean == null || mActivityInfoBean.getUrl() == null || TextUtils.isEmpty(mActivityInfoBean.getUrl())) {
            floatClick.setVisibility(View.GONE);
        } else {
            floatClick.setVisibility(View.VISIBLE);
            LoadPicUtil.load(mActivityInfoBean.getIcon(), floatClick);
        }

        afterLoginData();
    }


    private void afterLoginData() {
        if (AccountHelper.isLogin()) {
            if (AccountHelper.getUserPhonePOJO() != null && AccountHelper.getUid() != null) {
                login_tv.setVisibility(View.GONE);
                after_login.setVisibility(View.VISIBLE);
                name.setText(String.valueOf(AccountHelper.getUserPhonePOJO().getUserName()));
                coins.setText(String.format("金币：%s",  "0" ));
                id.setText("");
                if (AccountHelper.getUserPhonePOJO() != null && AccountHelper.getUserPhonePOJO().getLogo() != null &&
                        !TextUtils.isEmpty(AccountHelper.getUserPhonePOJO().getLogo())) {
                    Glide.with(mContext).load(AccountHelper.getUserPhonePOJO().getLogo())
                            .dontAnimate()
                            .into(icon);
                } else {
                    Glide.with(mContext).load(AccountHelper.getUserPhonePOJO().getLogo())
                            .dontAnimate()
                            .into(icon);
                }
            }
        } else {
            if (login_tv != null && after_login != null) {
                login_tv.setVisibility(View.VISIBLE);
                after_login.setVisibility(View.GONE);
                icon.setImageResource(R.drawable.photo_default);
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        getNewMessageHint();
        updateCoins();

    }

    /**
     * 更新金币数量
     */
    private void updateCoins() {
        if (AccountHelper.isLogin()) {

        }
    }

    private void getNewMessageHint() {
        OkHttpUtils.get()
                .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                .addHeader("uid", AccountHelper.getUid())
                .url(NetConstant.MESSAGE_NEW)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ivMessageHint.setVisibility(View.GONE);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            boolean hasNew = jsonObject.getBoolean("has_new");
                            if (hasNew) {
                                ivMessageHint.setVisibility(View.VISIBLE);
                            } else {
                                ivMessageHint.setVisibility(View.GONE);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ivMessageHint.setVisibility(View.GONE);
                        }
                    }
                });
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.mine_top) {
            if (AccountHelper.isLogin()) {
                if (AccountHelper.getUid() != null) {
                    startActivity(new Intent(mContext, MineSettingActivity.class));
                }
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }
            uClickEvent = "MyData";

        } else if (i == R.id.mine_click3) {
            //消息中心
            if (AccountHelper.isLogin()) {
                if (AccountHelper.getUid() != null) {
                    startActivity(new Intent(mContext, MyMessageActivity.class));
                }
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }
            uClickEvent = "MyMsg";

        } else if (i == R.id.mine_click4) {
            //我的收藏
            if (AccountHelper.isLogin()) {
                if (AccountHelper.getUid() != null) {
                    startActivity(new Intent(mContext, MyCollectionActivity.class));
                }
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }
            uClickEvent = "MyCollection";

        } else if (i == R.id.mine_click5) {
            //我参加的活动
            if (AccountHelper.isLogin()) {
                startActivity(new Intent(mContext, MyActiveActivity.class));
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }
            uClickEvent = "MyJoinActive";

        } else if (i == R.id.mine_task_center) {
            //任务中心
            if (AccountHelper.isLogin()) {
                startActivity(new Intent(mContext, TaskCenterActivity.class));
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }
            uClickEvent = "Task";

        } else if (i == R.id.mine_push_manager) {
            //推送管理
            startActivity(new Intent(mContext, PushManagerActivity.class));

        } else if (i == R.id.mine_click8) {
            //个人中心
            startActivity(new Intent(mContext, SettingActivity.class));
            uClickEvent = "MySetting";

        } else if (i == R.id.mine_click9) {
            //意见反馈
            if (AccountHelper.isLogin()) {
                if (!TextUtils.isEmpty(AccountHelper.getUserPhonePOJO().getMobile())) {
                    startActivity(new Intent(mContext, FeedbackActivity.class));
                } else {
                    fragmentStartActivity(RouterPath.BIND_ACCOUNT_PHONE_ACTIVITY);
                }
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }
            uClickEvent = "MyAdvice";


        } else if (i == R.id.mine_click10) {
            if (!AccountHelper.isLogin()) {
                RouterHelper.startActivity(getContext(), RouterPath.ACCOUNT_LOGIN_ACTIVITY);
                return;
            }
            //邀请好友
            Intent intent = new Intent(mContext, HtmlInviteActivity.class);
            String link = sContactUSPOJO.getActivitydesc().getLink();
            intent.putExtra(Constant.ZERO, TextUtils.isEmpty(link) ? "http://normal.h5_test.8btc.com/" : link);
            mContext.startActivity(intent);
            uClickEvent = "MyInvitate";

        } else if (i == R.id.mine_click11) {
            //联系我们
            startActivity(new Intent(mContext, ContactUsActivity.class));
            uClickEvent = "MyContactUs";
        } else if (i == R.id.mine_click12) {
            //我的帖子
            if (AccountHelper.isLogin()) {
                startActivity(new Intent(mContext, MyPostsActivity.class));
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }
            uClickEvent = "MyPosts";

        } else if (i == R.id.mine_click14) {
            //空头活动
            if (AccountHelper.isLogin() && AccountHelper.getUserPhonePOJO() != null) {
                if (!TextUtils.isEmpty(AccountHelper.getUserPhonePOJO().getMobile())) {
                    Intent intentAirDrop = new Intent(mContext, AirDropListActivity.class);
                    startActivity(intentAirDrop);
                } else {
                    fragmentStartActivity(RouterPath.BIND_ACCOUNT_PHONE_ACTIVITY);
                }
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }

        } else if (i == R.id.active_floatclick) {
            //活动邀请好友
            if (mActivityInfoBean == null) return;
            if (AccountHelper.isLogin() && AccountHelper.getUserPhonePOJO() != null) {
                if (!TextUtils.isEmpty(AccountHelper.getUserPhonePOJO().getMobile())) {
                    Intent intentFloat = new Intent(mContext, HtmlInviteActivity.class);
                    intentFloat.putExtra(Constant.ZERO, mActivityInfoBean.getUrl());
                    intentFloat.putExtra(Constant.ONE, String.valueOf(mActivityInfoBean.getId()));
                    mContext.startActivity(intentFloat);
                } else {
                    fragmentStartActivity(RouterPath.BIND_ACCOUNT_PHONE_ACTIVITY);
                }
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }

        } else if (i == R.id.mine_coins) {
            //金币商城
            if (AccountHelper.isLogin()) {
                startActivity(new Intent(mContext, TaskCenterActivity.class));
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }
            uClickEvent = "MyGold";

        } else if (i == R.id.mine_click_focus) {
            //我的关注
            if (AccountHelper.isLogin()) {
                fragmentStartActivity(RouterPath.MINE_FOCUS_AUTHOR_ACTIVITY);
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }
            uClickEvent = "MyFocus";

        } else if (i == R.id.mine_scan) {
            //扫描二维码
            if (AccountHelper.isLogin()) {
                requestCamera();
            } else {
                fragmentStartActivity(RouterPath.PHONE_LOGIN_ACTIVITY);
            }


        } else {
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("mineClickEvent", uClickEvent);
        UmengEvent.eventStatistics(mContext, Constant.U_MINE_EVENT, map);
    }

    //获取相机权限
    @SuppressLint("CheckResult")
    private void requestCamera() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (granted) {
                            LogUtils.i("author" + "start scan qrcode");
                            //扫一扫
                            Intent intent = new Intent(mContext, CustomQrCodeActivity.class);
                            startActivityForResult(intent, Constant.START_QRCODE);
                        } else {
                            DialogUtil.showOpenAppSettingDialog();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        DialogUtil.showOpenAppSettingDialog();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void LoginUI(MsgSuccess message) {
        if (message.msg.equals("LOGIN")) {
            if (login_tv == null) {
                return;
            }
            afterLoginData();
        }
        if (message.msg.equals("ICONCHANGE")) {
            String path = SharedPreferenceUtil.getString(mContext, Constant.ICON_PATH, "");
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            icon.setImageBitmap(bitmap);

        }

        if ("用户名修改".equals(message.msg)) {
            name.setText(message.tag);
        }
        //更新金币数量
        if (Constant.UPDATE_COINS.equals(message.msg)){
            updateCoins();
            EventBus.getDefault().removeStickyEvent(message);
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && data != null){
            switch (requestCode){
                case Constant.START_QRCODE:
                    String url = data.getStringExtra(Intents.Scan.RESULT);
                    LogUtils.i("author" + "qrcode:" + url);
                    analyzeQrCode(mContext, url);
                    break;
            }
        }
    }

    private static void analyzeQrCode(Context context, String url) {
        Uri uri = Uri.parse(url);
        if (TextUtils.isEmpty(url) || uri == null) {
            ToastUtil.show("请扫描正确的二维码");
            return;
        }
        if (uri.isHierarchical() && !TextUtils.isEmpty(uri.getQueryParameter("authcode"))) {
            String authcode = uri.getQueryParameter("authcode");
            Intent intent = new Intent(context, CaptureUserResultActivity.class);
            intent.putExtra(Constant.ONE, authcode);
            context.startActivity(intent);
        } else if (url.startsWith("http") && (url.contains("mall/item") || url.contains("mall/checkout"))) {
            RouterActivityHelper.openNewWeb(context, url);
        } else {
            String regexUri = DeepLinkUtils.regexUri(url);
            uri = Uri.parse(regexUri);
            DeepLinkUtils.jumpToTarget(context, uri);
        }
    }
}
